<template>
  <div>
    <div class="input-section">
      <div class="right">
        <el-input
          v-model="searchQuery"
          placeholder="请输入id"
          style="
            width: 500px;
            height: 40px;
            margin-bottom: 20px;
            margin-top: 20px;
          "
          :prefix-icon="Search"
          clearable
        />
        <el-button type="primary" @click="searchActivityById">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </div>
      <div class="button-group">
        <el-button @click="exportToExcel" type="success">导出 Excel</el-button>
        <el-button
          type="danger"
          @click="handleBatchDelete"
          @selection-change="handleSelectionChange"
          :disabled="selectedRows.length === 0"
        >批量删除</el-button>
      </div>
    </div>
    <!--社团活动申请表格-->
    <el-table
      ref="tableRef"
      :data="tableData"
      style="width: 100%; height: 520px"
      row-key="id"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="40" />
      <el-table-column prop="id" label="申请ID" width="70" sortable />
      <el-table-column prop="userId" label="申请用户ID" width="80" sortable />
      <el-table-column prop="targetId" label="活动/社团编号" width="80" />
      <el-table-column
        prop="type"
        label="申请类型"
        width="110"
        :filters="typeFilters"
        :filter-method="filterType"
        filter-placement="bottom-end"
      >
        <template #default="{ row }">
          <el-tag v-if="row.type === 8" type="success">举办活动</el-tag>
          <el-tag v-else-if="row.type === 9" type="danger">取消活动</el-tag>
          <el-tag v-else-if="row.type === 10" type="info">修改活动信息</el-tag>
          <el-tag v-else type="warning">未知类型</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="result"
        label="审核结果"
        width="110"
        :filters="resultFilters"
        :filter-method="filterResult"
        filter-placement="bottom-end"
      >
        <template #default="{ row }">
          <el-tag v-if="row.result === 0" type="warning">待审核</el-tag>
          <el-tag v-else-if="row.result === 1" type="success">通过</el-tag>
          <el-tag v-else-if="row.result === 2" type="danger">拒绝</el-tag>
          <el-tag v-else type="info">未知结果</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="reason" label="申请原因" width="110">
        <template #default="{ row }">
          <el-button size="small" @click="showReasonDialog(row)">查看</el-button>
        </template>
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="创建时间"
        width="100"
        sortable

      />
      <el-table-column
        prop="updateTime"
        label="更新时间"
        width="100"
        sortable
      />
      <el-table-column
        prop="startTime"
        label="开始时间"
        width="100"
        sortable
      />
      <el-table-column
        prop="endTime"
        label="结束时间时间"
        width="100"
        sortable
      />
      <el-table-column
        prop="isDelete"
        label="是否删除"
        width="100"
        :filters="deleteFilters"
        :filter-method="filterIsDelete"
        filter-placement="bottom-end"
      >
        <template #default="{ row }">
          <el-tag v-if="row.isDelete === 0" type="success">正常</el-tag>
          <el-tag v-else-if="row.isDelete === 1" type="warning">已删除</el-tag>
          <el-tag v-else type="info">未知结果</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template #default="{ row }">
          <el-button
            size="small"
            @click="handleApplicationReview(row, true)"
            type="success"
            :disabled="row.result !== 0 || row.isDelete === 1"
          >同意</el-button>
          <el-button
            size="small"
            @click="handleApplicationReview(row, false)"
            type="danger"
            :disabled="row.result !== 0 || row.isDelete === 1"
          >拒绝</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-section">
      <span class="record-count"> 共查询到 {{ total }} 条记录 </span>
      <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        v-model:page-size="pageSize"
        v-model:current-page="currentPage"
        :page-sizes="[4, 10, 20, 50]"
        @current-change="loadTableData"
        @size-change="loadTableData"
      />
    </div>
    <!--新增活动申请对话框-->
    <el-dialog title="新增活动申请" v-model="dialogVisible" width="700px">
      <el-form :model="form" label-width="120px">
        <el-form-item label="申请用户ID">
          <el-input v-model="form.userId" placeholder="请输入申请用户ID" />
        </el-form-item>
        <el-form-item label="申请原因">
          <el-input v-model="form.reason" placeholder="请输入申请原因" />
        </el-form-item>
        <el-form-item label="申请类型">
          <el-select v-model="form.type" placeholder="请选择申请类型">
            <el-option label="举办活动" value="8" />
            <el-option label="取消活动" value="9" />
            <el-option label="修改活动信息" value="10" />
          </el-select>
        </el-form-item>
        <el-form-item label="活动/社团编号">
          <el-input v-model="form.targetId" placeholder="请输入活动/社团编号" />
        </el-form-item>
        <el-form-item label="活动开始时间">
          <el-date-picker
            v-model="form.startTime"
            type="datetime"
            placeholder="请选择活动开始时间"
          />
        </el-form-item>
        <el-form-item label="活动结束时间">
          <el-date-picker
            v-model="form.endTime"
            type="datetime"
            placeholder="请选择活动结束时间"
          />
        </el-form-item>
        <el-form-item label="活动名称">
          <el-input
            v-model="form.additionalInfo.activityName"
            placeholder="请输入活动名称"
          />
        </el-form-item>
        <el-form-item label="活动标题">
          <el-input
            v-model="form.additionalInfo.activityTitle"
            placeholder="请输入活动标题"
          />
        </el-form-item>
        <el-form-item label="活动内容">
          <el-input
            type="textarea"
            v-model="form.additionalInfo.activityContent"
            placeholder="请输入活动内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">提交</el-button>
      </template>
    </el-dialog>
    <el-dialog title="申请原因详情" v-model="reasonDialogVisible" width="50%">
      <div style="white-space: pre-line">{{ currentReason }}</div>
      <template #footer>
        <el-button @click="reasonDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Search } from "@element-plus/icons-vue";
import { addActivityApplicationAPI,getActivityApplicationAllAPI,deleteActivityApplicationAPI } from "@/apis/activity";
import { doReviewAPI } from "@/apis/review";
import { useUserStore } from "@/stores/user";
import * as XLSX from 'xlsx';

// 导出为 Excel
const exportToExcel = () => {
  if (!tableData.value.length) {
    ElMessage.warning('没有可导出的数据');
    return;
  }
  console.log("表格数据：", tableData.value);
  // 提取你想要导出的字段
  const exportData = tableData.value.map((item) => ({
    '活动申请ID': item.id,
    '申请人ID': item.userId,
    '申请原因':item.reason
  }));

  const worksheet = XLSX.utils.json_to_sheet(exportData);
  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, worksheet, '社团信息');

  // 下载 Excel 文件
  XLSX.writeFile(workbook, `社团列表_${new Date().toISOString().slice(0, 10)}.xlsx`);
};

const userStore = useUserStore();
const total = ref(0); 
const currentPage = ref(1); 
const pageSize = ref(7); 
const searchQuery = ref(""); 

//加载表格数据
interface ActivityApplication {
  id: number;
  userId: number;
  targetId: number;
  type: number;
  result: number;
  createTime: string;
  updateTime: string;
  reason: string;
  isDelete: number;
  additionalInfo?: any;
}
const tableData = ref<ActivityApplication[]>([]);
const loadTableData = async () => {
  try {
    const response: any = await getActivityApplicationAllAPI(
      currentPage.value,
      pageSize.value,
      undefined
    );
    if (
      response.code === 0 &&
      response.data &&
      Array.isArray(response.data.records)
    ) {
      tableData.value = response.data.records; 
      total.value = response.data.total || 0;
    } else {
      tableData.value = [];
      total.value = 0;
      ElMessage.error("加载活动申请列表失败：" + response.message);
    }
  } catch (error) {
    tableData.value = [];
    total.value = 0;
    ElMessage.error("加载活动申请列表失败，请稍后重试");
  }
};
//根据社团活动申请id查找
const searchActivityById = async () => {
  if (!searchQuery.value.trim()) {
    ElMessage.warning("请输入活动ID或名称");
    return;
  }
  try {
    const response: any = await getActivityApplicationAllAPI(
      1,
      pageSize.value,
      searchQuery.value
    );
    if (response.code === 0 && response.data) {
      tableData.value = response.data.records || [];
      total.value = response.data.total || 0;
      if (tableData.value.length === 0) {
        ElMessage.warning("未找到匹配的活动");
      }
    } else {
      ElMessage.error(response.message || "搜索失败");
    }
  } catch (error) {
    ElMessage.error("搜索失败，请检查控制台");
  }
};
// 存储选中的行数据
const selectedRows = ref<ActivityApplication[]>([]);

// 处理选择变化
const handleSelectionChange = (rows: ActivityApplication[]) => {
  selectedRows.value = rows;
};
//处理批量删除
const handleBatchDelete = async () => {
  try {
    if (selectedRows.value.length === 0) {
      ElMessage.warning("请至少选择一条申请记录");
      return;
    }
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRows.value.length} 条活动申请吗？`,
      "删除确认",
      { type: "warning" }
    );
    const selectedIds = selectedRows.value.map((row) => row.id);
    const response: any = await deleteActivityApplicationAPI(selectedIds);
    if (response.code === 0) {
      ElMessage.success(`成功删除 ${selectedIds.length} 条活动申请`);
      await loadTableData();
      selectedRows.value = [];
    } else {
      throw new Error(response.message || "批量删除失败");
    }
  } catch (error: any) {
    if (error !== "cancel") {
      ElMessage.error(error.message || "批量删除失败");
    }
  }
};

// 活动申请审核（同意/拒绝）方法
const handleApplicationReview = async (
  row: ActivityApplication,
  isAccept: boolean
) => {
  // 1. 安全检查：确保只有未审核的申请可以操作
  if (row.result !== 0) {
    ElMessage.warning("该申请已审核，无法再次操作");
    return;
  }
  if (row.isDelete === 1) {
    ElMessage.warning("该申请已被删除，无法操作");
    return;
  }
  const actionText = isAccept ? "同意" : "拒绝";
  const resultValue = isAccept ? 1 : 2; // 1 = 同意, 2 = 拒绝
  try {
    // 2. 弹出对话框，让用户输入原因
    const { value: reason } = await ElMessageBox.prompt(
      `请输入${actionText}原因`,
      `${actionText}申请`,
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputValue: isAccept ? "同意该申请" : "",
        inputValidator: (val: string) => {
         
          if (!isAccept && (!val || val.trim() === "")) {
            return "拒绝原因不能为空";
          }
          return true;
        },
      }
    );
    // 3. 获取当前审核人的ID
    const reviewerId = userStore.id;
    if (!reviewerId) {
      ElMessage.error("无法获取当前用户信息，请重新登录");
      return;
    }
    // 4. 调用统一的审核接口 doReviewAPI
    const response: any = await doReviewAPI(
      reviewerId,   
      row.type,  
      row.id,     
      reason,     
      resultValue   
    );
    // 5. 处理后端返回的结果
    if (response && response.code === 0) {
      ElMessage.success(`活动申请已${actionText}`);
      await loadTableData(); // 成功后刷新列表
    } else {
      ElMessage.error(
        `${actionText}失败：` +
          (response && response.message
            ? response.message
            : "系统错误，请联系管理员")
      );
    }
  } catch (error: any) {
    if (error === "cancel") {
      ElMessage.info(`已取消${actionText}操作`);
    } else {
      ElMessage.error(
        `${actionText}活动申请失败，请查看控制台`
      );
      console.error("审核操作异常:", error);
    }
  }
};

// 重置搜索
const resetSearch = () => {
  searchQuery.value = "";
  currentPage.value = 1;
  loadTableData();
};

onMounted(() => {
  loadTableData();
});
// 筛选器
const typeFilters = [
  { text: "举办活动", value: 8 },
  { text: "取消活动", value: 9 },
  { text: "修改活动信息", value: 10 },
];

const resultFilters = [
  { text: "待审核", value: 0 },
  { text: "通过", value: 1 },
  { text: "拒绝", value: 2 },
];

const deleteFilters = [
  { text: "正常", value: 0 },
  { text: "已删除", value: 1 },
];

const reasonDialogVisible = ref(false);
const currentReason = ref("");

const showReasonDialog = (row: ActivityApplication) => {
  currentReason.value = row.reason || "无申请原因";
  reasonDialogVisible.value = true;
};

// 筛选方法
const filterType = (value: number, row: ActivityApplication) => row.type === value;
const filterResult = (value: number, row: ActivityApplication) => row.result === value;
const filterIsDelete = (value: number, row: ActivityApplication) => row.isDelete === value;

//添加申请
const dialogVisible = ref(false);

const form = ref({
  userId: 0,
  reason: "",
  type: 8, // 默认申请类型为举办活动
  targetId: 0,
  startTime: "",
  endTime: "",
  additionalInfo: {
    activityName: "",
    activityTitle: "",
    activityContent: "",
  },
});

const handleAdd = () => {
  dialogVisible.value = true;
};

// 专门适配该接口的时间格式化函数
const formatBackendTime = (date: Date | string): string => {
  if (!date) return "";

  const d = new Date(date);
  return (
    [
      d.getFullYear(),
      (d.getMonth() + 1).toString().padStart(2, "0"),
      d.getDate().toString().padStart(2, "0"),
    ].join("-") +
    " " +
    [
      d.getHours().toString().padStart(2, "0"),
      d.getMinutes().toString().padStart(2, "0"),
      d.getSeconds().toString().padStart(2, "0"),
    ].join(":")
  );
};

const handleSubmit = async () => {
  try {
    const submitData = {
      userId: Number(form.value.userId),
      reason: form.value.reason,
      type: Number(form.value.type),
      targetId: Number(form.value.targetId),
      startTime: formatBackendTime(form.value.startTime),
      endTime: formatBackendTime(form.value.endTime),
      additionalInfo: form.value.additionalInfo,
    };
    const response: any = await addActivityApplicationAPI(submitData);

    if (response.code === 0) {
      ElMessage.success("提交成功");
      dialogVisible.value = false;
      loadTableData();
    } else {
      throw new Error(response.message || `后端返回错误码: ${response.code}`);
    }
  } catch (error: any) {
    ElMessage.error(`提交失败: ${error.message}`);
  }
};
</script>

<style scoped>
.input-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.button-group {
  display: flex;
  gap: 10px;
}

.pagination-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
}

.record-count {
  font-size: 14px;
  color: #666;
}
.right {
  display: flex;
  align-items: center;
  gap: 10px;
}
</style>
